<template>
  <div class="roleSet">
    <div class="content__body">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="权限类型" prop="includeType">
          <el-radio-group
            v-model="formData.includeType"
            size="mini"
            @change="includeTypeChange"
          >
            <el-radio-button label="1">包含</el-radio-button>
            <el-radio-button class="btn-last" label="0">不包含</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <P class="content__body--title">
        【包含】是指拥有选中权限，【不包含】是指拥有选中权限以外的所有权限
      </P>
      <div>
        <div v-for="item in resourceList" :key="item.id">
          <el-checkbox
            v-model="item.isActive"
            :indeterminate="item.isIndeterminate"
            @change="handleAllCheck(item)"
            >{{ item.resourceGroupName }}</el-checkbox
          >
          <br />
          <el-checkbox-group
            v-model="item.isActiveChild"
            :key="item.id"
            @change="handleCheckedCitiesChange(item)"
          >
            <el-checkbox
              v-for="i in item.resourceList"
              :key="i.id"
              :label="i.id"
              >{{ i.resourceName }}</el-checkbox
            >
          </el-checkbox-group>
          <el-divider></el-divider>
        </div>
      </div>
    </div>

    <div class="content__footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from "vue";
import NotifMessage from "/@/utils/message/notification";
import {
  postResourceGroupList,
  postRoleResourceAuth,
  postGetRoleResourceAuth
} from "/@/api/resource";
import { cloneDeep } from "lodash-es";

export default defineComponent({
  name: "resourceSet",
  emits: ["closeDrawer"],
  props: {
    roleId: {
      type: Number,
      require: true
    }
  },
  setup(props, { emit }) {
    let formRef = ref<HTMLFormElement | null>(null) as any;
    let state = reactive({
      resourceList: [],
      resourceAuth: [],
      formData: {
        includeType: "0"
      }
    });

    const formRules = ref({
      roleName: [
        { required: true, message: "请输入角色名称", trigger: "blur" }
      ],
      roleDesc: [{ required: true, message: "请输入角色描述", trigger: "blur" }]
    });

    // const onGetMenuList = async () => {
    //   try {
    //     treeLoading.value = true;
    //     // const { code, data } = await getMenuList({});
    //     // if (code === 200) {
    //     //   treeData.value = data;
    //     //   if (props.mode === "edit") {
    //     //     getCurrentMenu();
    //     //   }
    //     // }
    //   } catch (err) {
    //     console.log(err);
    //   } finally {
    //     treeLoading.value = false;
    //   }
    // };
    const includeTypeChange = () => {
      // 切换权限类型的时候，对权限进行反选操作
      const { resourceList } = state;
      resourceList.map((item: any) => {
        const allResource = item.resourceList.map((i: any) => i.id); // 所有节点ID集合
        const { isActiveChild } = item; // 已选节点
        const oppositeResource = allResource.filter(
          (i: any) => !isActiveChild.includes(i)
        ); // 得到反选节点
        // 往回赋值
        let isActive = false;
        let isIndeterminate = false;
        if (oppositeResource.length === item.resourceList.length) {
          // 全选
          isActive = true;
        }
        if (
          oppositeResource.length > 0 &&
          oppositeResource.length < item.resourceList.length
        ) {
          isIndeterminate = true;
        }
        item.isActiveChild = oppositeResource;
        item.isActive = isActive;
        item.isIndeterminate = isIndeterminate;
      });
    };

    const handleCancel = () => {
      emit("closeDrawer");
    };

    const fnFilterData = list => {
      return list.map(item => {
        return { id: item };
      });
    };
    const handleSubmit = async () => {
      let newGroupList = [];
      const copyResourceList = cloneDeep(state.resourceList);
      copyResourceList.map(item => {
        if (item.isActiveChild.length) {
          newGroupList.push({
            id: item.id,
            resourceGroupKey: item.resourceGroupKey,
            resourceList: fnFilterData(item.isActiveChild)
          });
        }
      });

      if (state.formData.includeType === "1" && newGroupList.length < 1) {
        NotifMessage.error("请至少选择一个");
        return;
      }
      const params = {
        roleId: props.roleId,
        includeType: state.formData.includeType,
        resGroupList: newGroupList
      };

      try {
        const { code, message } = await postRoleResourceAuth(params);
        if (code === 200) {
          NotifMessage.success(message);
          handleCancel();
        } else {
          message && NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };
    // 请求表格数据
    async function getTableData(obj: object = {}) {
      try {
        const { code, data } = await postResourceGroupList(obj);
        if (code === 200) {
          data.forEach(item => {
            item.isActive = false;
            item.isActiveChild = [];
            item.isIndeterminate = false;
          });
          state.resourceList = data;
        }
      } catch (err) {
        console.log(err);
      }
    }

    async function getInitResourceAuth(obj: object = {}) {
      try {
        const { code, data } = await postGetRoleResourceAuth(obj);
        if (code === 200) {
          state.formData.includeType = data.includeType;
          state.resourceAuth = data.resGroupList;
        }
      } catch (err) {
        console.log(err);
      }
    }

    const initTable = async () => {
      await getTableData();
      await getInitResourceAuth({ roleId: props.roleId });
      state.resourceAuth.length &&
        state.resourceAuth.forEach(item => {
          state.resourceList.forEach(i => {
            if (i.id === item.id) {
              const newList =
                item.resourceList.length &&
                item.resourceList.map(x => {
                  return x.id;
                });
              i.isActiveChild = newList;
              if (i.resourceList.length === newList.length) {
                i.isActive = true;
              } else {
                i.isIndeterminate = true;
              }
            }
          });
        });
    };

    // onGetMenuList();
    // getTableData();
    initTable();

    const handleCheckedCitiesChange = item => {
      if (item.isActiveChild.length === item.resourceList.length) {
        item.isActive = true;
      } else {
        item.isActive = false;
      }

      if (
        item.isActiveChild.length > 0 &&
        item.isActiveChild.length !== item.resourceList.length
      ) {
        item.isIndeterminate = true;
      } else {
        item.isIndeterminate = false;
      }
    };

    const handleAllCheck = item => {
      if (item.isActive) {
        item.isActiveChild = item.resourceList.map(x => {
          return x.id;
        });
      } else {
        item.isActiveChild = [];
      }
      if (
        item.isActiveChild.length > 0 &&
        item.isActiveChild.length !== item.resourceList.length
      ) {
        item.isIndeterminate = true;
      } else {
        item.isIndeterminate = false;
      }
    };

    return {
      formRef,
      ...toRefs(state),
      formRules,
      includeTypeChange,
      handleCheckedCitiesChange,
      handleAllCheck,
      handleCancel,
      handleSubmit
    };
  }
});
</script>

<style lang="scss" scoped>
.roleSet {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  .content__body {
    width: 100%;
    flex: 1;
    padding: 15px;
    overflow-y: auto;
    &--title {
      font-size: 14px;
      color: #606266;
      line-height: 32px;
      margin-bottom: 10px;
    }
  }
  .content__footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
    height: 60px;
    border-top: 1px solid rgba(0, 21, 41, 0.15);
    padding: 15px;
  }
}

.btn-last {
  :deep .el-radio-button__original-radio:checked + .el-radio-button__inner {
    background: red;
    border-color: red;
    box-shadow: -1px 0 0 red;
  }
}
</style>
